let fs = require('fs');
let sqlserver = require('mssql');
let addSerial = false
let addFulltext = false
let addInpatientInterval = true
let addOperationInterval = true
let recordslimit = 1000
let index = 'mr'

// let dbConfigSource = {
//     server: '10.160.12.192',
//     database: 'MR_FS_DB',
//     user: 'sa',
//     password: 'Docimax@123',
//     port: 1433
// };
let dbConfigSource = {
    server: '172.30.199.163\\dev',
    database: 'MR_FS_DB',
    user: 'sa',
    password: 'Docimax@123',
    port: 1433
};
let db = require('./db')

async function getFullText(sid, pool) {
    sql = "select OCRCatalogue,OCRCatalogueID,OCRAllText from VOCR_ResultInfo where Success=1 and OCRImagePriSerialNo='" + sid + "'"
    var r = await pool.request().query(sql);
    let rd = r.recordset
    if (rd === undefined) {
        return []
    }
    return rd
}
async function getPriSerialNo(id, pool) {
    sql = "select PriSerialNo from VMDPMS_MedicalPatientBase where PBaseID='" + id + "'"
    var r = await pool.request().query(sql);
    let rd = r.recordset[0]
    if (rd === undefined) {
        return -1
    }
    return rd['PriSerialNo']
}
async function processMore(id, pool) {
    sql = "select CreateTime ,LastModifyTime from VDoctor where IPB_ID='" + id + "' and DoctorType='编码员'"

    var r = await pool.request().query(sql);
    let rd = r.recordset[0]
    if (rd === undefined) {
        return {}
    }
    let c = rd['CreateTime']
    let l = rd['LastModifyTime']
    return {
        c,
        l
    }

}

async function getInpatientInterval(mrid, admissionDateTime, hospitalizedTimes) {
    let sql = "select DischargeDateTime from VBase where mrid='" + mrid + "' and HospitalizedTimes=" + (hospitalizedTimes--)
    var r = await pool.request().query(sql);
    let rd = r.recordset[0]
    if (rd === undefined) {
        return -1
    }
    return rd['DischargeDateTime'] - admissionDateTime //ms distance
}
async function getExtInfo(element, pool) {

    var id = element["ID"]
    element.Diagnosis = await db.getExt(id, "IPB_ID", "VDiagnosis", () => pool)
    element.Doctor = await db.getExtWithType(id, "IPB_ID", "VDoctor", "DoctorType", "DoctorName", [], () => pool)
    element.VAllergyDiagnosis = await db.getExt(id, "IPB_ID", "VAllergyDiagnosis", () => pool)
    element.VClinicDiagnosis = await db.getExt(id, "IPB_ID", "VClinicDiagnosis", () => pool)
    element.VContact = await db.getExt(id, "IPB_ID", "VContact", () => pool)
    element.VFee = await db.getExtWithType(id, "IPB_ID", "VFee", "FeeClassName", "FeeValue", [], () => pool)
    element.VICU = await db.getExt(id, "IPB_ID", "VICU", () => pool)
    element.VOperate = await db.getExt(id, "IPB_ID", "VOperate", () => pool)
    element.VSurgery = await db.getExt(id, "IPB_ID", "VSurgery", () => pool)
    element.VTransfer = await db.getExt(id, "IPB_ID", "VTransfer", () => pool)

    let {
        c,
        l
    } = await processMore(id, pool)
    element['CodeTime'] = c
    element['LastModifiedTime'] = l
    let ht = element['HospitalizedTimes'];
    if (ht > 1 && addInpatientInterval) {
        let inpatientInterval = getInpatientInterval(element['mrid'], element['AdmissionDateTime'], ht)
        element['InpatientInterval'] = inpatientInterval / 1000 / 3600 //hours distance
    }
    if (addSerial) {
        let priSerialNo = await getPriSerialNo(id, pool)

        element['PriSerialNo'] = priSerialNo
    }
    if (addFulltext && priSerialNo != undefined && priSerialNo != -1) {
        let r = await getFullText(priSerialNo, pool)
        element['FullText'] = r
    }
    return element
}
let con = undefined
async function getConnection() {
    if (con == undefined) {
        con = await sqlserver.connect(dbConfigSource);
    }
    return con;
}

async function getData(strsql, pool) {
    let data = [];
    try {
        let rs = await pool.request().query(strsql);
        //console.log(rs);
        for (let i = 0; i < rs.recordset.length; i++) {
            let element = rs.recordset[i]
            let d = await getExtInfo(element, pool)
            data.push(d);
            console.log(i / rs.recordset.length)
        }
        return data
    } catch (error) {
        console.log(error);
    } finally {
        //await pool.close();
    }

}


function getDateString(d) {
    let s = d.getFullYear().toString() + "-" +
        (d.getMonth() + 1).toString() + "-" +
        d.getDate().toString()
    return s
}

async function trandData(start, end, timeinterval) {
    console.log(start);
    var s = new Date();
    pool = await getConnection();
    for (let d = start; d < end; d.addDays(timeinterval)) {
        try {
            console.log('process ' + getDateString(d));
            let xd = new Date(d)
            let sql = "select * from vbase where DischargeDateTime>='" + getDateString(d) + "' and DischargeDateTime<'" + getDateString(xd.addDays(timeinterval)) + "'"
            console.log(sql);
            let data = await getData(sql, pool)
            console.log('save' + data.length);
            let ss = JSON.stringify(data)
            //console.log(ss);
            fs.appendFileSync(".\\data.json", ss)
            console.log('step finished');
        } catch (err) {
            console.log(err);
        }
    }
    await pool.close();
    let spend = new Date() - s;
    console.log('spend:' + spend.toString());
}

trandData(new Date('2018/1/1'), new Date('2018/3/1'), 1)

module.exports.TarnsNew = (interval) => {
    let start = Date.now()
    start = start - interval * 24 * 3600
    trandData(new Date(start), new Date(Date.now()), 1)
}